'use strict';
import React from 'react';
import {FlatList, StyleSheet, View, ViewPropTypes} from 'react-native';
import PropTypes from 'prop-types'

class WrapContainer extends React.PureComponent {

    static propTypes = {
        style: ViewPropTypes.style,  // 最外层的样式
        data: PropTypes.array.isRequired,
        keyExtractor: PropTypes.func.isRequired,
        numColumns: PropTypes.number.isRequired,
        renderItem: PropTypes.func.isRequired,
        itemColumnMargin: PropTypes.number, // 列间距
        itemRowMargin: PropTypes.number, // 行间距
        useFlatList: PropTypes.bool,  // 使用FlatList的横向布局模式
        extraData: PropTypes.any
    };

    static defaultProps = {
        data: [],
        itemColumnMargin: 0,
        itemRowMargin: 0,
        useFlatList: false
    };

    constructor(props) {
        super(props);
        this.state = {containerWidth: 0}
    }


    renderContent = (props) => {
        const {containerWidth} = this.state;
        const {data, keyExtractor, style, numColumns, itemColumnMargin, itemRowMargin, renderItem} = props;
        const wrapItemWidth = Math.floor((containerWidth - itemColumnMargin * (numColumns - 1)) / numColumns);
        return (
            <View style={[styles.wrapContainer, style]} onLayout={this._onLayout}>
                {data.map((item, index) => {
                    const marginLeft = index % numColumns === 0 ? 0 : itemColumnMargin;
                    const marginTop = index < numColumns ? 0 : itemRowMargin;
                    const element = renderItem({item, index, width: wrapItemWidth});
                    const key = keyExtractor(item, index);
                    return (
                        <View key={key} style={[styles.wrapItemContainer, {
                            width: wrapItemWidth,
                            marginLeft,
                            marginTop
                        }, element.props.containerStyle]}>
                            {element}
                        </View>
                    )
                })}
            </View>
        )
    };

    renderFlatList = (props) => {
        return (
            <FlatList
                {...props}
            />
        )
    };

    _onLayout = (event) => {
        const layout = event.nativeEvent.layout;
        const {containerWidth} = this.state;
        if (Math.round(containerWidth) !== Math.round(layout.width)) {
            this.setState({containerWidth: layout.width})
        }
    };

    render() {
        const {useFlatList, ...others} = this.props;
        return (
            useFlatList ? <this.renderFlatList {...others} /> : <this.renderContent {...others} />
        );
    }
}

const styles = StyleSheet.create({
    wrapContainer: {
        flexDirection: 'row',
        flexWrap: 'wrap',
    },
    wrapItemContainer: {
        // backgroundColor: 'blue',
    }
});

export default WrapContainer